﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Security;
using System.Data.Linq;

namespace Hxsoft.AppV1.Module
{
	public partial class User : IOwner
	{
		public Guid? OwnerId
		{
			get { return this.UserId; }
		}
	}



	/// <summary>
	/// Users 类。
	/// </summary>
	public static partial class Users
	{
		public const string INFO_TYPE = "User";
		public const string Regex_Pattern_UserName = @"\w[\w|\d]{3,}";
		public const string Regex_Pattern_Password = @"[\w|\d]{6,20}";
		public const string AdministratorUserName = "Administrator";

		#region IsOnline
		/// <summary>
		/// 该用户是否已登录
		/// </summary>
		/// <param name="userId"></param>
		/// <returns></returns>
		public static bool IsOnline(Guid userId)
		{		
			if(Users.IsAdministrator(Users.GetUserName(userId))) return false;
			return Membership.GetUser(userId, false).IsOnline;
		}
		#endregion


		#region GetCurrentUser
		/// <summary>
		/// 当前用户的标识。
		/// </summary>
		public static Guid? CurrentUserId
		{
			get { return App.Context.CurrentUserId; }
		}

		/// <summary>
		/// 当前用户。
		/// </summary>
		public static User CurrentUser
		{
			get { return App.Context.CurrentUser; }
		}

		/// <summary>
		/// 当前用户的用户名。
		/// </summary>
		public static string CurrentUserName
		{
			get { return App.Context.CurrentUserName; }
		}

		/// <summary>
		/// 取得当前用户的标识。
		/// </summary>
		/// <param name="userIsOnline">是否更新最后活动时间。</param>
		/// <returns>当前用户标识。</returns>
		public static Guid? GetCurrentUserId(bool userIsOnline)
		{
			return App.Context.GetCurrentUserId(userIsOnline);
		}

		/// <summary>
		/// 取得当前用户。
		/// </summary>
		/// <param name="userIsOnline">是否更新最后活动时间。</param>
		/// <returns>当前用户。</returns>
		public static User GetCurrentUser(bool userIsOnline)
		{
			return App.Context.GetCurrentUser(userIsOnline);
		}

		/// <summary>
		/// 取得当前用户用户名。
		/// </summary>
		/// <param name="userIsOnline">是否更新最后活动时间。</param>
		/// <returns>当前用户用户名。</returns>
		public static string GetCurrentUserName(bool userIsOnline)
		{
			return App.Context.GetCurrentUserName(userIsOnline);
		}
		#endregion



		#region GetUser

		/// <summary>
		/// 根据用户标识获取用户名。
		/// </summary>
		/// <param name="o"></param>
		/// <param name="userId"></param>
		/// <returns></returns>
		public static string GetUserName(this System.Data.Linq.Table<User> o, Guid? userId)
		{
			if (!userId.HasValue) return "";
			return (from p in o where p.UserId == userId.Value select p.UserName).SingleOrDefault();
		}
		/// <summary>
		/// 根据用户标识获取用户名。
		/// </summary>
		/// <param name="userId"></param>
		/// <returns></returns>
		public static string GetUserNameById(Guid? userId)
		{
			GenericModuleDataContext dc = new GenericModuleDataContext();
			dc.ObjectTrackingEnabled = false;
			return dc.Users.GetUserName(userId);
		}
		/// <summary>
		/// 获取系统用户
		/// </summary>
		/// <param name="o"></param>
		/// <returns></returns>
		private static List<User> GetUsers(this System.Data.Linq.Table<User> o)
		{
			return o.ToList();
		}
		/// <summary>
		/// 获取系统用户
		/// </summary>
		/// <returns></returns>
		public static List<User> GetUsers()
		{
			GenericModuleDataContext dc = new GenericModuleDataContext();
			dc.ObjectTrackingEnabled = false;
			return dc.Users.GetUsers();
		}

		/// <summary>
		/// 根据用户标识获取用户名。
		/// </summary>
		/// <param name="userId">用户的标识。</param>
		/// <returns>用户标识对应的用户名。</returns>
		public static string GetUserName(Guid userId)
		{
			MembershipUser mUser = Membership.GetUser(userId, false);
			if (mUser != null)
				return mUser.UserName;
			return null;
		}

		/// <summary>
		/// 获取用户信息。
		/// </summary>
		/// <param name="username">用户名。</param>
		/// <returns>用户信息。</returns>
		public static User GetUser(string username)
		{
			MembershipUser mUser = Membership.GetUser(username, false);
			if (mUser == null) return null;
			User user = new User();
			return MembershipToUser(mUser, user);
		}

		/// <summary>
		/// 获取用户信息。
		/// </summary>
		/// <param name="username">用户名。</param>
		/// <returns>用户信息。</returns>
		public static User GetUser(Guid userId)
		{
			MembershipUser mUser = Membership.GetUser(userId, false);
			if (mUser == null) return null;
			User user = new User();
			return MembershipToUser(mUser, user);
		}


		public static AdvUser GetAdvUser(string userName)
		{
			var user = GetUser(userName);	
			GenericModuleDataContext dc = new GenericModuleDataContext();
			return dc.AdvUsers.FirstOrDefault(p => p.UserId == user.UserId);
		}

		/// <summary>
		/// 获取用户的标识。
		/// </summary>
		/// <param name="username">用户名。</param>
		/// <returns>用户的标识。</returns>
		public static Guid? GetUserId(string username)
		{
			if (string.IsNullOrEmpty(username))
				return null;

			Dictionary<string, Guid?> ids = GenericCacheContainer.Instance.UserIdByUsernameDictionary;
			if (ids.ContainsKey(username))
				return ids[username];

			lock (ids)
			{
				if (!ids.ContainsKey(username))
				{
					MembershipUser mUser = Membership.GetUser(username, false);
					if (mUser == null) return null;
					try
					{
						ids[username] = (Guid?)mUser.ProviderUserKey;
					}
					catch (IndexOutOfRangeException err)
					{
						ids.Clear();
						ids[username] = (Guid?)mUser.ProviderUserKey;
					}
				}
			}
			return ids[username];
		}




		#endregion



		#region Exists
		/// <summary>
		/// 验证用户是否存在。
		/// </summary>
		/// <param name="userName">用户名。</param>
		/// <returns>布尔值表示用户是否存在。</returns>
		public static bool Exists(string userName)
		{
			return GetUser(userName) == null ? false : true;
		}

		/// <summary>
		/// 验证用户是否存在。
		/// </summary>
		/// <param name="userKey">用户的标识。</param>
		/// <returns>布尔值表示用户是否存在。</returns>
		public static bool Exists(Guid userKey)
		{
			return GetUserName(userKey) == null ? false : true;
		}

		/// <summary>
		/// 验证指定的邮件地址是否已经存在。
		/// </summary>
		/// <param name="email">进行验证的邮件地址。</param>
		/// <returns>布尔值表示指定的邮件地址是否已经存在。</returns>
		public static bool ExistsEmail(string email)
		{
			MembershipUserCollection users = Membership.FindUsersByEmail(email);
			return users.Count > 0;
		}
		#endregion

		#region CheckUserExists
		internal static bool _CheckCurrentSystemUserExists(string userName)
		{
			return Exists(userName);
		}

		/// <summary>
		/// 检测用户名在整个系统群中是否存在。
		/// </summary>
		/// <param name="userName">进行检测的用户名。</param>
		/// <returns>布尔值表示用户名在整个系统群中是否存在。</returns>
		public static bool CheckUserExists(string userName)
		{
			if (_CheckCurrentSystemUserExists(userName))
				return true;
			return UserIntegration.ExistsIntegrationSubsystemUser(null, userName);
		}
		#endregion



		#region CheckUserPassword
		internal static bool _CheckCurrentSystemUserPassword(string userName, string password)
		{
			return Membership.ValidateUser(userName, password);
		}
		#endregion



		#region IsAdministrator
		/// <summary>
		/// 验证指定的用户是否为管理员。
		/// </summary>
		/// <param name="username">验证的用户。</param>
		/// <returns>布尔值表示指定的用户是否为管理员。</returns>
		public static bool IsAdministrator(string username)
		{
			if (string.IsNullOrEmpty(username)) return false;

			Dictionary<string, bool> d = GenericCacheContainer.Instance.AdministratorDictionary;
			if (d.Count > 0)
			{
				if (d.ContainsKey(username))
					return d[username];
				return false;
			}

			lock (d)
			{
				if (!d.ContainsKey(username))
				{
					var users = Roles.GetUsersInRole(null, Roles.AdministratorRoleName);
					try
					{
						if (users != null)
						{
							foreach (var user in users)
								d[user] = true;
						}
						if (!d.ContainsKey(username)) d[username] = false;
					}
					catch (IndexOutOfRangeException err)
					{
						d.Clear();
						if (users != null)
						{
							foreach (var user in users)
								d[user] = true;
						}
						if (!d.ContainsKey(username)) d[username] = false;
					}
				}
			}
			return d[username];
		}
		#endregion



		#region IsOwner
		/// <summary>
		/// 验证指定的用户是否为所有者。
		/// </summary>
		/// <param name="username">验证的用户。</param>
		/// <param name="vUserName">进行比较的用户名。</param>
		/// <returns>布尔值表示指定的用户是否为所有者。</returns>
		public static bool IsOwner(string username, string vUserName)
		{
			if (!string.IsNullOrEmpty(username))
			{
				return username == vUserName;
			}

			return false;
		}
		#endregion


		#region GetUserLastLoginTime
		/// <summary>
		/// 获取当前用户上一次登录的时间
		/// </summary>
		/// <param name="userName"></param>
		/// <returns></returns>
		public static DateTime? GetUserLastLoginTime(string userName)
		{
			if (string.IsNullOrEmpty(userName)) return null;

			GenericModuleDataContext dc = new GenericModuleDataContext();
			dc.ObjectTrackingEnabled = false;

			var q = from p in dc.Logs
					where p.Operation == Users.PermissionCode.Login.ToString() && 
						  p.InfoType == INFO_TYPE && p.InfoId == userName					
					select p;				

			var logList = q.OrderByDescending(p=>p.LogTime).Take(2).ToList();
			
			return logList.LastOrDefault().LogTime;
		}
		#endregion


		#region GetUserLoginCount
		/// <summary>
		/// 获取当前用户登录的次数
		/// </summary>
		/// <param name="userName"></param>
		/// <returns></returns>
		public static int GetUserLoginCount(string userName)
		{
			if (string.IsNullOrEmpty(userName)) return 0;

			GenericModuleDataContext dc = new GenericModuleDataContext();
			dc.ObjectTrackingEnabled = false;

			var q = from p in dc.Logs
					where p.Operation == Users.PermissionCode.Login.ToString() &&
						  p.InfoType == INFO_TYPE && p.InfoId == userName
					select p;			
			return q.Count();
		}


		#endregion


		#region GetUserConfirm
		/// <summary>
		/// 获取用户验证信息。
		/// </summary>
		/// <param name="userId">用户的标识。</param>
		/// <returns>用户验证信息。</returns>
		public static UserConfirm GetUserConfirm(Guid userId)
		{
			return UserConfirms.GetItem(userId);
		}
		#endregion
	}




	/// <summary>
	/// Users 类操作部分。
	/// </summary>
	public static partial class Users
	{
		#region BuildUserConfirm
		/// <summary>
		/// 生成用户确认信息。
		/// </summary>
		/// <param name="userId">生成的用户标识。</param>
		/// <param name="password">用户注册时的密码。</param>
		/// <returns>用户确认信息。</returns>
		public static UserConfirm BuildUserConfirm(Guid userId, string password)
		{
			UserConfirm info = new UserConfirm();
			info.UserId = userId;
			info.IsConfirm = false;
			info.ConfirmCode = RndString(50);
			info.Password = password;
			info.CreationDate = DateTime.Now;

			return UserConfirms.Update(info);
		}

		/// <summary> 
		/// 获取随机字符串 
		/// </summary> 
		/// <param name="strLength">字符串长度</param> 
		/// <param name="Seed">随机函数种子值</param> 
		/// <returns>指定长度的随机字符串</returns> 
		public static string RndString(int strLength, params int[] Seed)
		{
			string strSep = ",";
			char[] chrSep = strSep.ToCharArray();

			//因1与l不容易分清楚，所以去除 
			string strChar = "1,2,3,4,5,6,7,8,9,0,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z"
				+ ",A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z";

			string[] aryChar = strChar.Split(chrSep, strChar.Length);

			string strRandom = string.Empty;
			Random Rnd;
			if (Seed != null && Seed.Length > 0)
			{
				Rnd = new Random(Seed[0]);
			}
			else
			{
				Rnd = new Random();
			}

			//生成随机字符串 
			for (int i = 0; i < strLength; i++)
			{
				strRandom += aryChar[Rnd.Next(aryChar.Length)];
			}

			return strRandom;
		}
		#endregion




		#region Confirm
		/// <summary>
		/// 用户确认。
		/// </summary>
		/// <param name="userId">进行确认的用户标识。</param>
		/// <param name="confirmCode">确认码。</param>
		public static bool Confirm(Guid userId, string confirmCode)
		{
			bool b = UserConfirms.Confirm(userId, confirmCode);

			if (b)
			{
				_SetApprovedStatus(userId, true);

				// 记录日志
				Logs.Insert(new GenericModuleDataContext(), ResourceId, null, INFO_TYPE, userId.ToString(), "Confirm", confirmCode);
			}

			return b;
		}
		#endregion




		#region Login & Logout
		internal static bool _LoginCurrentSystem(string userName, string password)
		{
			return App.Context.Login(userName, password);
		}

		internal static bool _LoginNotValidate(string sourceSystemName, string userName)
		{
			bool pass = _LoginCurrentSystemNotValidate(userName);
			if(pass)
				UserIntegration.LoginNotValidateIntegrationSubsystem(sourceSystemName, userName);
			return pass;
		}

		internal static bool _LoginNotValidate(string sourceSystemName, Guid userId)
		{
			string userName = GetUserName(userId);
			if (string.IsNullOrEmpty(userName)) return false;
			return _LoginNotValidate(sourceSystemName, userName);
		}

		internal static bool _LoginCurrentSystemNotValidate(string userName)
		{
			FormsAuthentication.SetAuthCookie(userName, true);
			return true;
		}

		internal static bool _LoginCurrentSystemNotValidate(Guid userId)
		{
			string userName = GetUserName(userId);
			if(string.IsNullOrEmpty(userName)) return false;
			return _LoginCurrentSystemNotValidate(userName);
		}

		/// <summary>
		/// 登录系统。
		/// </summary>
		/// <param name="userName">用户名。</param>
		/// <param name="password">密码。</param>
		/// <returns>是否登录成功。</returns>
		public static bool Login(string userName, string password)
		{
			//GetLoginRight(true);	// 权限验证

			bool pass = _LoginCurrentSystem(userName, password);
			if (pass)
				UserIntegration.LoginIntegrationSubsystem(null, userName, password);

			// 记录日志

			Logs.Insert(new GenericModuleDataContext(), ResourceId, (int)PermissionCode.Login, INFO_TYPE, userName, PermissionCode.Login.ToString(), pass.ToString());			

			return pass;
		}



		/// <summary>
		/// 退出登录。
		/// </summary>
		/// <param name="userName">退出登录的用户。</param>
		/// <returns>是否成功退出。</returns>
		internal static bool _LogoutCurrentSystem(string userName)
		{
			return App.Context.Logout(userName);
		}
		
		/// <summary>
		/// 退出登录。
		/// </summary>
		/// <returns>是否成功退出。</returns>
		public static bool Logout()
		{
			string userName = CurrentUserName;
			if (userName == null) return false;

			bool b = _LogoutCurrentSystem(userName);
			UserIntegration.LogoutIntegrationSubsystem(null, userName);

			// 记录日志
			Logs.Insert(new GenericModuleDataContext(), ResourceId, null, INFO_TYPE, userName, "Logout", null);

			return b;
		}
		#endregion




		#region RegisterUser
		internal static User MembershipToUser(MembershipUser mUser, User user)
		{
			if (user == null) user = new User();

			user.UserId = (Guid)mUser.ProviderUserKey;
			user.UserName = mUser.UserName;
			user.Password = null;
			user.PasswordQuestion = mUser.PasswordQuestion;
			user.PasswordAnswer = null;
			user.Email = mUser.Email;
			user.IsApproved = mUser.IsApproved;
			user.IsLockedOut = mUser.IsLockedOut;
			user.LastLoginDate = mUser.LastLoginDate;
			user.CreationDate = mUser.CreationDate;

			return user;
		}

		internal static User _CreateCurrentSystemUser(User user, out UserCreateStatus statusCode)
		{
			MembershipCreateStatus status;
			//user.IsApproved = true;
			MembershipUser mUser = Membership.CreateUser(user.UserName, user.Password, user.Email, user.PasswordQuestion, user.PasswordAnswer, user.IsApproved, out status);

			statusCode = CreateUserException.MembershipCreateStatusToUserCreateStatus(status);
			return MembershipToUser(mUser, user);
		}

		/// <summary>
		/// 创建用户。
		/// </summary>
		/// <param name="user">创建的用户信息。</param>
		/// <param name="statusCode">创建状态码。</param>
		/// <returns>创建的用户。</returns>
		internal static User _CreateUser(User user, out UserCreateStatus statusCode)
		{
			string password = user.Password;
			user = _CreateCurrentSystemUser(user, out statusCode);
			user.Password = password;

			if (statusCode == UserCreateStatus.Success)
			{
				// 创建整合子系统的用户
				UserIntegration.CreateIntegrationSubsystemUser(null, user.UserName, user.Password, user.Email);
			}
			return user;
		}

		internal static User _RegisterUser(User user)
		{
			UserCreateStatus status = default(UserCreateStatus);
			user = _CreateUser(user, out status);

			if (status != UserCreateStatus.Success)
				throw new CreateUserException(status);

			return user;
		}

		/// <summary>
		/// 注册用户。
		/// </summary>
		/// <param name="user">注册的用户资料。</param>
		/// <returns>注册的用户。</returns>
		public static User RegisterUser(User user)
		{
			GenericModuleDataContext dc = new GenericModuleDataContext();
			GetRegisterRight(dc, true);	// 权限验证

			var u = _RegisterUser(user);

			// 记录日志
			Logs.Insert(dc, ResourceId, (int)PermissionCode.Register, INFO_TYPE, u.UserName, PermissionCode.Register.ToString(), u.UserId.ToString());

			return u;
		}



		/// <summary>
		/// 注册管理员用户。
		/// </summary>
		/// <param name="password">管理员用户的密码。</param>
		internal static void RegisterAdministratorUser(string password)
		{
			if (!Exists(AdministratorUserName))
			{
				UserCreateStatus statusCode = UserCreateStatus.Success;
				_CreateUser(new User { UserName = AdministratorUserName, Password = password }, out statusCode);
			}
			else
			{
				string rePassword = ResetPassword(AdministratorUserName);
				ChangePassword(AdministratorUserName, rePassword, password);
			}

			Roles.RegisterAdministratorRole();
			Roles._AddUserToRole(AdministratorUserName, null, Roles.AdministratorRoleName);
		}

		/// <summary>
		/// 注册管理员用户。
		/// </summary>
		/// <returns>管理员用户的密码。</returns>
		internal static void RegisterAdministratorUser()
		{
			RegisterAdministratorUser("123456");
		}
		#endregion



		#region ChangePassword
		/// <summary>
		/// 修改用户密码。
		/// </summary>
		/// <param name="userName">要修改密码的用户名。</param>
		/// <param name="oldPassword">旧密码。</param>
		/// <returns>布尔值表示是否修改成功。</returns>
		internal static bool _ChangeCurrentSystemUserPassword(string userName, string newPassword)
		{
			bool b = false;
			MembershipUser user = Membership.GetUser(userName);
			if (user != null)
			{
				string password = user.ResetPassword();
				b = user.ChangePassword(password, newPassword);
			}

			return b;
		}

		/// <summary>
		/// 修改密码。
		/// </summary>
		/// <param name="userName">修改密码的用户名。</param>
		/// <param name="password">修改的密码。</param>
		/// <returns>布尔值代表是否修改成功。</returns>
		internal static bool _ChangePassword(string userName, string password)
		{
			bool b = _ChangeCurrentSystemUserPassword(userName, password);

			if (b)
			{
				// 修改整合子系统的用户密码
				UserIntegration.ChangeIntegrationSubsystemUserPassword(null, userName, password);

				//记录修改密码
				var userId=Users.GetUserId(userName);
				
				if (ChangePasswordRecords.Exists(userId))
				{
					var record = ChangePasswordRecords.GetItem(userId.Value);
					record.ChangeDate = DateTime.Now;
					ChangePasswordRecords.Update(record);
				}
				else
				{
					ChangePasswordRecords.Insert(new ChangePasswordRecord { UserId = userId.Value, ChangeDate = DateTime.Now });
				}
							
			}
			return b;
		}

		/// <summary>
		/// 修改用户密码。
		/// </summary>
		/// <param name="userName">要修改密码的用户名。</param>
		/// <param name="oldPassword">旧密码。</param>
		/// <param name="newPassword">新密码。</param>
		/// <returns>布尔值表示是否修改成功。</returns>
		internal static bool _ChangePassword(string userName, string oldPassword, string newPassword)
		{
			if (!Membership.ValidateUser(userName, oldPassword))
				return false;
			UserIntegration.ChangeIntegrationSubsystemUserPassword(null, userName, oldPassword, newPassword, string.Empty);
			return _ChangePassword(userName, newPassword);
		}

		/// <summary>
		/// 修改用户密码。
		/// </summary>
		/// <param name="userName">要修改密码的用户名。</param>
		/// <param name="oldPassword">旧密码。</param>
		/// <param name="newPassword">新密码。</param>
		/// <returns>布尔值表示是否修改成功。</returns>
		public static bool ChangePassword(string userName, string oldPassword, string newPassword)
		{
			GenericModuleDataContext dc = new GenericModuleDataContext();

			GetChangePasswordRight(dc, Users.GetUser(userName), true);	// 权限验证
			bool b = _ChangePassword(userName, oldPassword, newPassword);
			
			// 记录日志
			Logs.Insert(dc, ResourceId, (int)PermissionCode.Update, INFO_TYPE, userName, PermissionCode.Update.ToString() + "/ChangePassword", b.ToString());

			return b;
		}
		#endregion



		#region ResetPassword
		/// <summary>
		/// 重置用户密码。
		/// </summary>
		/// <param name="userName">要重设密码的用户名。</param>
		/// <returns>重设的密码。</returns>
		internal static string _ResetPassword(string userName)
		{
			MembershipUser user = Membership.GetUser(userName);
			string password = user.ResetPassword();

			// 修改整合子系统的用户密码
			UserIntegration.ChangeIntegrationSubsystemUserPassword(null, userName, password);

			return password;
		}

		/// <summary>
		/// 重置用户密码。
		/// </summary>
		/// <param name="userName">要重设密码的用户名。</param>
		/// <returns>重设的密码。</returns>
		public static string ResetPassword(string userName)
		{
			GenericModuleDataContext dc = new GenericModuleDataContext();

			GetResetPasswordRight(dc, Users.GetUser(userName), true);	// 权限验证
			var password = _ResetPassword(userName);

			// 记录日志
			Logs.Insert(dc, ResourceId, (int)PermissionCode.Setting, INFO_TYPE, userName, PermissionCode.Setting.ToString() + "/ResetPassword", password);

			return password;
		}
		#endregion



		#region SetApprovedStatus
		/// <summary>
		/// 设置用户的认可状态。
		/// </summary>
		/// <param name="userName">用户名。</param>
		/// <param name="isApproved">认可状态。</param>
		internal static void _SetApprovedStatus(Guid userId, bool isApproved)
		{
			MembershipUser user = Membership.GetUser(userId);
			user.IsApproved = isApproved;
			Membership.UpdateUser(user);
		}

		/// <summary>
		/// 设置用户的认可状态。
		/// </summary>
		/// <param name="userName">用户名。</param>
		/// <param name="isApproved">认可状态。</param>
		internal static void _SetApprovedStatus(string userName, bool isApproved)
		{
			MembershipUser user = Membership.GetUser(userName);
			user.IsApproved = isApproved;
			Membership.UpdateUser(user);
		}

		/// <summary>
		/// 设置用户的认可状态。
		/// </summary>
		/// <param name="userName">用户名。</param>
		/// <param name="isApproved">认可状态。</param>
		public static void SetApprovedStatus(string userName, bool isApproved)
		{
			GenericModuleDataContext dc = new GenericModuleDataContext();

			GetSetApprovedStatusRight(dc, Users.GetUser(userName), true);	// 权限验证
			_SetApprovedStatus(userName, isApproved);

			// 记录日志
			Logs.Insert(dc, ResourceId, (int)PermissionCode.Setting, INFO_TYPE, userName, PermissionCode.Setting.ToString() + "/ApprovedStatus", isApproved.ToString());
		}
		#endregion



		#region Unlock
		/// <summary>
		/// 解锁用户。
		/// </summary>
		/// <param name="userName">要解锁的用户名。</param>
		/// <returns>布尔值表示是否解锁成功。</returns>
		internal static bool _Unlock(string userName)
		{
			MembershipUser user = Membership.GetUser(userName);
			return user.UnlockUser();
		}

		/// <summary>
		/// 解锁用户。
		/// </summary>
		/// <param name="userName">要解锁的用户名。</param>
		/// <returns>布尔值表示是否解锁成功。</returns>
		public static bool Unlock(string userName)
		{
			GenericModuleDataContext dc = new GenericModuleDataContext();

			GetUnlockRight(dc, Users.GetUser(userName), true);	// 权限验证
			bool b = _Unlock(userName);

			// 记录日志
			Logs.Insert(dc, ResourceId, (int)PermissionCode.Setting, INFO_TYPE, userName, PermissionCode.Setting.ToString() + "/Unlock", b.ToString());

			return b;
		}
		#endregion



		#region UpdateEmail
		/// <summary>
		/// 更新用户的邮件地址。
		/// </summary>
		/// <param name="userName">用户名。</param>
		/// <param name="email">要更新的邮件地址。</param>
		internal static void _UpdateEmail(string userName, string email)
		{
			MembershipUser user = Membership.GetUser(userName);
			user.Email = email;
			Membership.UpdateUser(user);
		}

		/// <summary>
		/// 更新用户的邮件地址。
		/// </summary>
		/// <param name="userName">用户名。</param>
		/// <param name="email">要更新的邮件地址。</param>
		public static void UpdateEmail(string userName, string email)
		{
			GenericModuleDataContext dc = new GenericModuleDataContext();

			GetUpdateEmailRight(dc, Users.GetUser(userName), true);	// 权限验证
			_UpdateEmail(userName, email);

			// 记录日志
			Logs.Insert(dc, ResourceId, (int)PermissionCode.Update, INFO_TYPE, userName, PermissionCode.Update.ToString() + "/Email", email);
		}
		#endregion



		#region Delete
		internal static bool _DeleteCurrentSystemUser(string userName)
		{
			GenericModuleDataContext dc = new GenericModuleDataContext();
			UserConfirms.DeleteByParent(dc, GetUser(userName));
			ChangePasswordRecords.DeleteByParent(dc, GetUser(userName));
			TeamMembers.DeleteByParent(dc, GetUser(userName));
			return Membership.DeleteUser(userName, true);
		}

		/// <summary>
		/// 删除指定的用户。
		/// </summary>
		/// <param name="userName">要删除的用户标识。</param>
		/// <returns>如果用户已删除，则为 true；否则为 false。</returns>
		internal static bool _Delete(string userName)
		{
			bool b = _DeleteCurrentSystemUser(userName);

			if (b)
			{
				// 删除整合子系统的用户。
				UserIntegration.DeleteIntegrationSubsystemUser(null, userName);
			}
			return b;
		}

		/// <summary>
		/// 删除指定的用户。
		/// </summary>
		/// <param name="userId">要删除的用户标识。</param>
		/// <returns>如果用户已删除，则为 true；否则为 false。</returns>
		internal static bool _Delete(Guid userId)
		{
			string userName = GetUserName(userId);
			if (string.IsNullOrEmpty(userName)) return false;
			return _Delete(userName);
		}

		/// <summary>
		/// 删除指定的用户。
		/// </summary>
		/// <param name="userName">要删除的用户标识。</param>
		/// <returns>如果用户已删除，则为 true；否则为 false。</returns>
		public static bool Delete(string userName)
		{
			GenericModuleDataContext dc = new GenericModuleDataContext();

			GetDeleteRight(dc, Users.GetUser(userName), true);
			bool b = _Delete(userName);

			// 记录日志
			Logs.Insert(dc, ResourceId, (int)PermissionCode.Delete, INFO_TYPE, userName, PermissionCode.Delete.ToString(), b.ToString());

			return b;
		}
		#endregion


		public static void SetAdvUserName(Guid userId,string userName)
		{
			GenericModuleDataContext dc = new GenericModuleDataContext();

			AdvUser user = dc.AdvUsers.FirstOrDefault(p => p.UserId == userId);
			if (user == null)
				throw new ObjectNotExistsException(Res.Operation_ObjectNotExists);

			GetAdvSettingRight(dc, user, true);	// 权限验证

			user.UserName = userName;
			user.LoweredUserName = userName;

			try
			{
				dc.SubmitChanges(ConflictMode.ContinueOnConflict);
			}
			catch (ChangeConflictException e)
			{
				foreach (ObjectChangeConflict occ in dc.ChangeConflicts)
				{
					occ.Resolve(RefreshMode.KeepCurrentValues);
				}
			}

			// 记录日志			
			Logs.Insert(dc, ResourceId, (int)PermissionCode.AdvSetting, INFO_TYPE, userName, PermissionCode.AdvSetting.ToString(), userName);
		}

	}



	/// <summary>
	/// Users 类对应操作权限部分。
	/// </summary>
	public static partial class Users
	{
		#region GetRegisterRight
		/// <summary>
		/// 获取当前用户是否有注册权限。
		/// </summary>
		/// <param name="dc">数据容器。</param>
		/// <param name="triggerException">当未通过权限验证的时候是否引发异常。</param>
		/// <returns>布尔值表示当前用户是否有注册权限。</returns>
		public static bool GetRegisterRight(GenericModuleDataContext dc, bool triggerException)
		{
			string userName = CurrentUserName;
			int permissionCode = (int)PermissionCode.Register;
			bool b = dc.AccessController.GetUserIsHasPermission<object>(userName, null, ResourceId, permissionCode);

			if(triggerException && !b)
				throw new PermissionException(userName, null, ResourceId, permissionCode, Res.PermissionExceptionMessage);
			return b;
		}

		/// <summary>
		/// 获取当前用户是否有注册权限。
		/// </summary>
		/// <param name="triggerException">当未通过权限验证的时候是否引发异常。</param>
		/// <returns>布尔值表示当前用户是否有注册权限。</returns>
		public static bool GetRegisterRight(bool triggerException)
		{
			return GetRegisterRight(new GenericModuleDataContext(), triggerException);
		}

		/// <summary>
		/// 获取当前用户是否有注册权限。
		/// </summary>
		/// <returns>布尔值表示当前用户是否有注册权限。</returns>
		public static bool GetRegisterRight()
		{
			return GetRegisterRight(false);
		}
		#endregion



		#region GetLoginRight
		/// <summary>
		/// 获取当前用户是否有登录权限。
		/// </summary>
		/// <param name="dc">数据容器。</param>
		/// <param name="triggerException">当未通过权限验证的时候是否引发异常。</param>
		/// <returns>布尔值表示当前用户是否有登录权限。</returns>
		public static bool GetLoginRight(GenericModuleDataContext dc, bool triggerException)
		{
			string userName = CurrentUserName;
			int permissionCode = (int)PermissionCode.Login;
			bool b = dc.AccessController.GetUserIsHasPermission<object>(userName, null, ResourceId, permissionCode);

			if (triggerException && !b)
				throw new PermissionException(userName, null, ResourceId, permissionCode, Res.PermissionExceptionMessage);
			return b;
		}

		/// <summary>
		/// 获取当前用户是否有登录权限。
		/// </summary>
		/// <param name="triggerException">当未通过权限验证的时候是否引发异常。</param>
		/// <returns>布尔值表示当前用户是否有登录权限。</returns>
		public static bool GetLoginRight(bool triggerException)
		{
			return GetLoginRight(new GenericModuleDataContext(), triggerException);
		}

		/// <summary>
		/// 获取当前用户是否有登录权限。
		/// </summary>
		/// <returns>布尔值表示当前用户是否有登录权限。</returns>
		public static bool GetLoginRight()
		{
			return GetLoginRight(false);
		}
		#endregion



		#region GetCreateRight
		/// <summary>
		/// 获取当前用户是否有创建用户的权限。
		/// </summary>
		/// <param name="dc">数据容器。</param>
		/// <param name="triggerException">当未通过权限验证的时候是否引发异常。</param>
		/// <returns>布尔值表示当前用户是否有创建用户的权限。</returns>
		public static bool GetCreateRight(GenericModuleDataContext dc, bool triggerException)
		{
			string userName = CurrentUserName;
			int permissionCode = (int)PermissionCode.Create;
			bool b = dc.AccessController.GetUserIsHasPermission<object>(userName, null, ResourceId, permissionCode);

			if (triggerException && !b)
				throw new PermissionException(userName, null, ResourceId, permissionCode, Res.PermissionExceptionMessage);
			return b;
		}

		/// <summary>
		/// 获取当前用户是否有创建用户的权限。
		/// </summary>
		/// <param name="triggerException">当未通过权限验证的时候是否引发异常。</param>
		/// <returns>布尔值表示当前用户是否有创建用户的权限。</returns>
		public static bool GetCreateRight(bool triggerException)
		{
			return GetCreateRight(new GenericModuleDataContext(), triggerException);
		}

		/// <summary>
		/// 获取当前用户是否有创建用户的权限。
		/// </summary>
		/// <returns>布尔值表示当前用户是否有创建用户的权限。</returns>
		public static bool GetCreateRight()
		{
			return GetCreateRight(false);
		}
		#endregion



		#region GetUpdateRight
		/// <summary>
		/// 获取当前用户是否有更新指定用户资料的权限。
		/// </summary>
		/// <param name="dc">数据容器。</param>
		/// <param name="user">更新的用户。</param>
		/// <param name="triggerException">当未通过权限验证的时候是否引发异常。</param>
		/// <returns>布尔值表示当前用户是否有更新指定用户资料的权限。</returns>
		public static bool GetUpdateRight(GenericModuleDataContext dc, User user, bool triggerException)
		{
			string userName = string.IsNullOrEmpty(CurrentUserName) ? user.UserName : CurrentUserName;
			int permissionCode = (int)PermissionCode.Update;
			bool b = dc.AccessController.GetUserIsHasPermission<User>(userName, user, ResourceId, permissionCode);

			if (triggerException && !b)
				throw new PermissionException(userName, user, ResourceId, permissionCode, Res.PermissionExceptionMessage);
			return b;
		}

		/// <summary>
		/// 获取当前用户是否有更新指定用户资料的权限。
		/// </summary>
		/// <param name="user">更新的用户。</param>
		/// <param name="triggerException">当未通过权限验证的时候是否引发异常。</param>
		/// <returns>布尔值表示当前用户是否有更新指定用户资料的权限。</returns>
		public static bool GetUpdateRight(User user, bool triggerException)
		{
			return GetUpdateRight(new GenericModuleDataContext(), user, triggerException);
		}

		/// <summary>
		/// 获取当前用户是否有更新指定用户资料的权限。
		/// </summary>
		/// <param name="user">更新的用户。</param>
		/// <returns>布尔值表示当前用户是否有更新指定用户资料的权限。</returns>
		public static bool GetUpdateRight(User user)
		{
			return GetUpdateRight(user, false);
		}



		/// <summary>
		/// 获取当前用户是否有修改指定用户密码的权限。
		/// </summary>
		/// <param name="dc">数据容器。</param>
		/// <param name="user">修改的用户。</param>
		/// <param name="triggerException">当未通过权限验证的时候是否引发异常。</param>
		/// <returns>布尔值表示当前用户是否有修改指定用户密码的权限。</returns>
		public static bool GetChangePasswordRight(GenericModuleDataContext dc, User user, bool triggerException)
		{
			return GetUpdateRight(dc, user, triggerException);
		}
		
		/// <summary>
		/// 获取当前用户是否有修改指定用户密码的权限。
		/// </summary>
		/// <param name="user">修改的用户。</param>
		/// <param name="triggerException">当未通过权限验证的时候是否引发异常。</param>
		/// <returns>布尔值表示当前用户是否有修改指定用户密码的权限。</returns>
		public static bool GetChangePasswordRight(User user, bool triggerException)
		{
			return GetChangePasswordRight(new GenericModuleDataContext(), user, triggerException);
		}
		
		/// <summary>
		/// 获取当前用户是否有修改指定用户密码的权限。
		/// </summary>
		/// <param name="user">修改的用户。</param>
		/// <returns>布尔值表示当前用户是否有修改指定用户密码的权限。</returns>
		public static bool GetChangePasswordRight(User user)
		{
			return GetChangePasswordRight(user, false);
		}



		/// <summary>
		/// 获取当前用户是否有修改指定用户 Email 的权限。
		/// </summary>
		/// <param name="dc">数据容器。</param>
		/// <param name="user">修改的用户。</param>
		/// <param name="triggerException">当未通过权限验证的时候是否引发异常。</param>
		/// <returns>布尔值表示当前用户是否有修改指定用户 Email 的权限。</returns>
		public static bool GetUpdateEmailRight(GenericModuleDataContext dc, User user, bool triggerException)
		{
			return GetUpdateRight(dc, user, triggerException);
		}
		
		/// <summary>
		/// 获取当前用户是否有修改指定用户 Email 的权限。
		/// </summary>
		/// <param name="user">修改的用户。</param>
		/// <param name="triggerException">当未通过权限验证的时候是否引发异常。</param>
		/// <returns>布尔值表示当前用户是否有修改指定用户 Email 的权限。</returns>
		public static bool GetUpdateEmailRight(User user, bool triggerException)
		{
			return GetUpdateEmailRight(new GenericModuleDataContext(), user, triggerException);
		}
		
		/// <summary>
		/// 获取当前用户是否有修改指定用户 Email 的权限。
		/// </summary>
		/// <param name="user">修改的用户。</param>
		/// <returns>布尔值表示当前用户是否有修改指定用户 Email 的权限。</returns>
		public static bool GetUpdateEmailRight(User user)
		{
			return GetUpdateEmailRight(user, false);
		}
		#endregion


		private static readonly HashSet<string> _settedExcludeColumns = typeof(AdvUser).GetEntityColumnNames(new string[] {
				"UserName",
				"LoweredUserName"
			}, true);


		#region GetSettingRight
		/// <summary>
		/// 获取当前用户是否有设置指定用户信息的权限。
		/// </summary>
		/// <param name="dc">数据容器。</param>
		/// <param name="user">设置的用户。</param>
		/// <param name="triggerException">当未通过权限验证的时候是否引发异常。</param>
		/// <returns>布尔值表示当前用户是否有设置指定用户信息的权限。</returns>
		public static bool GetSettingRight(GenericModuleDataContext dc, User user, bool triggerException)
		{
			string userName = CurrentUserName;
			int permissionCode = (int)PermissionCode.Setting;
			bool b = dc.AccessController.GetUserIsHasPermission<User>(userName, user, ResourceId, permissionCode);

			if (triggerException && !b)
				throw new PermissionException(userName, user, ResourceId, permissionCode, Res.PermissionExceptionMessage);
			return b;
		}
		/// <summary>
		/// 获取当前用户是否有高级设置指定用户信息的权限
		/// </summary>
		/// <param name="dc"></param>
		/// <param name="user"></param>
		/// <param name="triggerException"></param>
		/// <returns></returns>
		public static bool GetAdvSettingRight(GenericModuleDataContext dc, AdvUser user, bool triggerException)
		{
			string userName = CurrentUserName;
			int permissionCode = (int)PermissionCode.AdvSetting;
			bool b = dc.AccessController.GetUserIsHasPermission<AdvUser>(userName, user, ResourceId, permissionCode);

			if (triggerException && !b)
				throw new PermissionException(userName, user, ResourceId, permissionCode, Res.PermissionExceptionMessage);
			return b;
		}


		/// <summary>
		/// 获取当前用户是否有设置指定用户信息的权限。
		/// </summary>
		/// <param name="user">设置的用户。</param>
		/// <param name="triggerException">当未通过权限验证的时候是否引发异常。</param>
		/// <returns>布尔值表示当前用户是否有设置指定用户信息的权限。</returns>
		public static bool GetSettingRight(User user, bool triggerException)
		{
			return GetSettingRight(new GenericModuleDataContext(), user, triggerException);
		}

		/// <summary>
		/// 获取当前用户是否有高级设置指定用户信息的权限
		/// </summary>
		/// <param name="user"></param>
		/// <param name="triggerException"></param>
		/// <returns></returns>
		public static bool GetAdvSettingRight(AdvUser user, bool triggerException)
		{
			return GetAdvSettingRight(new GenericModuleDataContext(), user, triggerException);
		}

		/// <summary>
		/// 获取当前用户是否有设置指定用户信息的权限。
		/// </summary>
		/// <param name="user">设置的用户名。</param>
		/// <returns>布尔值表示当前用户是否有设置指定用户信息的权限。</returns>
		public static bool GetSettingRight(User user)
		{
			return GetSettingRight(user, false);
		}

		/// <summary>
		/// 获取当前用户是否有高级设置指定用户信息的权限
		/// </summary>
		/// <param name="user"></param>
		/// <returns></returns>
		public static bool GetAdvSettingRight(AdvUser user)
		{
			return GetAdvSettingRight(user, false);
		}

		/// <summary>
		/// 获取当前用户是否有重置指定用户密码的权限。
		/// </summary>
		/// <param name="dc">数据容器。</param>
		/// <param name="user">重置的用户。</param>
		/// <param name="triggerException">当未通过权限验证的时候是否引发异常。</param>
		/// <returns>布尔值表示当前用户是否有重置指定用户密码的权限。</returns>
		public static bool GetResetPasswordRight(GenericModuleDataContext dc, User user, bool triggerException)
		{
			return GetSettingRight(dc, user, triggerException);
		}
		
		/// <summary>
		/// 获取当前用户是否有重置指定用户密码的权限。
		/// </summary>
		/// <param name="user">重置的用户。</param>
		/// <param name="triggerException">当未通过权限验证的时候是否引发异常。</param>
		/// <returns>布尔值表示当前用户是否有重置指定用户密码的权限。</returns>
		public static bool GetResetPasswordRight(User user, bool triggerException)
		{
			return GetResetPasswordRight(new GenericModuleDataContext(), user, triggerException);
		}

		/// <summary>
		/// 获取当前用户是否有重置指定用户密码的权限。
		/// </summary>
		/// <param name="user">重置的用户。</param>
		/// <returns>布尔值表示当前用户是否有重置指定用户密码的权限。</returns>
		public static bool GetResetPasswordRight(User user)
		{
			return GetResetPasswordRight(user, false);
		}



		/// <summary>
		/// 获取当前用户是否有设置指定用户认可状态的权限。
		/// </summary>
		/// <param name="dc">数据容器。</param>
		/// <param name="user">设置的用户。</param>
		/// <param name="triggerException">当未通过权限验证的时候是否引发异常。</param>
		/// <returns>布尔值表示当前用户是否有设置指定用户认可状态的权限。</returns>
		public static bool GetSetApprovedStatusRight(GenericModuleDataContext dc, User user, bool triggerException)
		{
			return GetSettingRight(dc, user, triggerException);
		}

		/// <summary>
		/// 获取当前用户是否有设置指定用户认可状态的权限。
		/// </summary>
		/// <param name="user">设置的用户。</param>
		/// <param name="triggerException">当未通过权限验证的时候是否引发异常。</param>
		/// <returns>布尔值表示当前用户是否有设置指定用户认可状态的权限。</returns>
		public static bool GetSetApprovedStatusRight(User user, bool triggerException)
		{
			return GetSetApprovedStatusRight(new GenericModuleDataContext(), user, triggerException);
		}

		/// <summary>
		/// 获取当前用户是否有设置指定用户认可状态的权限。
		/// </summary>
		/// <param name="user">设置的用户。</param>
		/// <returns>布尔值表示当前用户是否有设置指定用户认可状态的权限。</returns>
		public static bool GetSetApprovedStatusRight(User user)
		{
			return GetSetApprovedStatusRight(user, false);
		}



		/// <summary>
		/// 获取当前用户是否有解锁指定用户的权限。
		/// </summary>
		/// <param name="dc">数据容器。</param>
		/// <param name="user">解锁的用户。</param>
		/// <param name="triggerException">当未通过权限验证的时候是否引发异常。</param>
		/// <returns>布尔值表示当前用户是否有解锁指定用户的权限。</returns>
		public static bool GetUnlockRight(GenericModuleDataContext dc, User user, bool triggerException)
		{
			return GetSettingRight(dc, user, triggerException);
		}

		/// <summary>
		/// 获取当前用户是否有解锁指定用户的权限。
		/// </summary>
		/// <param name="user">解锁的用户。</param>
		/// <param name="triggerException">当未通过权限验证的时候是否引发异常。</param>
		/// <returns>布尔值表示当前用户是否有解锁指定用户的权限。</returns>
		public static bool GetUnlockRight(User user, bool triggerException)
		{
			return GetUnlockRight(new GenericModuleDataContext(), user, triggerException);
		}

		/// <summary>
		/// 获取当前用户是否有解锁指定用户的权限。
		/// </summary>
		/// <param name="user">解锁的用户。</param>
		/// <returns>布尔值表示当前用户是否有解锁指定用户的权限。</returns>
		public static bool GetUnlockRight(User user)
		{
			return GetUnlockRight(user, false);
		}
		#endregion



		#region GetDeleteRight
		/// <summary>
		/// 获取当前用户是否有删除指定用户信息的权限。
		/// </summary>
		/// <param name="dc">数据容器。</param>
		/// <param name="user">删除的用户。</param>
		/// <param name="triggerException">当未通过权限验证的时候是否引发异常。</param>
		/// <returns>布尔值表示当前用户是否有删除指定用户信息的权限。</returns>
		public static bool GetDeleteRight(GenericModuleDataContext dc, User user, bool triggerException)
		{
			string userName = CurrentUserName;
			int permissionCode = (int)PermissionCode.Delete;
			bool b = dc.AccessController.GetUserIsHasPermission<User>(userName, user, ResourceId, permissionCode);

			if (triggerException && !b)
				throw new PermissionException(userName, user, ResourceId, permissionCode, Res.PermissionExceptionMessage);
			return b;
		}

		/// <summary>
		/// 获取当前用户是否有删除指定用户信息的权限。
		/// </summary>
		/// <param name="user">删除的用户。</param>
		/// <param name="triggerException">当未通过权限验证的时候是否引发异常。</param>
		/// <returns>布尔值表示当前用户是否有删除指定用户信息的权限。</returns>
		public static bool GetDeleteRight(User user, bool triggerException)
		{
			return GetDeleteRight(new GenericModuleDataContext(), user, triggerException);
		}

		/// <summary>
		/// 获取当前用户是否有删除指定用户信息的权限。
		/// </summary>
		/// <param name="user">删除的用户。</param>
		/// <returns>布尔值表示当前用户是否有删除指定用户信息的权限。</returns>
		public static bool GetDeleteRight(User user)
		{
			return GetDeleteRight(user, false);
		}
		#endregion
	}




	/// <summary>
	/// 用户创建状态。
	/// </summary>
	public enum UserCreateStatus
	{
		Success,
		InvalidUserName,
		InvalidPassword,
		InvalidQuestion,
		InvalidAnswer,
		InvalidEmail,
		DuplicateUserName,
		DuplicateEmail,
		UserRejected,
		InvalidProviderUserKey,
		DuplicateProviderUserKey,
		ProviderError
	}



	/// <summary>
	/// 创建用户例外。
	/// </summary>
	public class CreateUserException : MembershipCreateUserException
	{
		public CreateUserException() : base() { }
		public CreateUserException(UserCreateStatus statusCode) : base((MembershipCreateStatus)statusCode) { }

		internal static UserCreateStatus MembershipCreateStatusToUserCreateStatus(MembershipCreateStatus mStatus)
		{
			return (UserCreateStatus)mStatus;
		}
	}




	/// <summary>
	/// Users 类后台管理部分。
	/// </summary>
	public static partial class Users
	{
		public static bool GetManageListRight()
		{
			GenericModuleDataContext dc = new GenericModuleDataContext();
			return dc.AccessController.GetUserIsHasPermission<object>(Users.CurrentUserName, null, Users.ResourceId, (int)Users.PermissionCode.Delete);
		}



		public class UserForManageList
		{
			public Guid UserId { get; set; }
			public string UserName { get; set; }
			public string Email { get; set; }
			public DateTime LastLoginDate { get; set; }
			public DateTime CreationDate { get; set; }
			public bool IsApproved { get; set; }
			public bool IsLockedOut { get; set; }
		}

		

		public static PaginationInfo<List<UserForManageList>> GetPaginationManageList(string keyword, int pageSize, int currentPage)
		{
			GenericModuleDataContext dc = new GenericModuleDataContext();
			dc.ObjectTrackingEnabled = false;

			var q = from p in dc.Users
					orderby p.CreationDate descending
					select new UserForManageList { UserId = p.UserId, UserName = p.UserName, Email = p.Email, LastLoginDate = p.LastLoginDate, CreationDate = p.CreationDate, IsApproved = p.IsApproved, IsLockedOut = p.IsLockedOut };

			if (!string.IsNullOrEmpty(keyword))
				q = q.Where(p => p.UserName.Contains(keyword));

			PaginationInfo<List<UserForManageList>> pageInfo = new PaginationInfo<List<UserForManageList>>();
			pageInfo.PageSize = pageSize;
			pageInfo.CurrentPage = currentPage;
			pageInfo.RecordCount = q.Count();
			pageInfo.Records = q.Skip((currentPage - 1) * pageSize).Take(pageSize).ToList();
			return pageInfo;
		}

		public static PaginationInfo<List<UserForManageList>> GetPaginationSelectorList(bool? isApproved, string keyword, string[] usernames, int pageSize, int currentPage)
		{
			GenericModuleDataContext dc = new GenericModuleDataContext();
			dc.ObjectTrackingEnabled = false;

			var q = from p in dc.Users
					orderby p.CreationDate descending
					select new UserForManageList
					{
						UserId = p.UserId,
						UserName = p.UserName,
						Email = p.Email,
						LastLoginDate = p.LastLoginDate,
						CreationDate = p.CreationDate,
						IsApproved = p.IsApproved,
						IsLockedOut = p.IsLockedOut
					};
			if (isApproved.HasValue)
				q = q.Where(p => p.IsApproved == isApproved.Value);

			if (!string.IsNullOrEmpty(keyword))
				q = q.Where(p => p.UserName.Contains(keyword));

			if (usernames != null)
			{
				if (usernames.Length > 0)
					q = q.Where(p => usernames.Contains(p.UserName));
				else
					q = q.Where(p => 1 == 0);
			}
			var q2 = q.ToList();

			PaginationInfo<List<UserForManageList>> pageInfo = new PaginationInfo<List<UserForManageList>>();
			pageInfo.PageSize = pageSize;
			pageInfo.CurrentPage = currentPage;
			pageInfo.RecordCount = q2.Count();
			pageInfo.Records = q2.Skip((currentPage - 1) * pageSize).Take(pageSize).ToList();
			return pageInfo;
		}
	}
}